import 'package:in_app_purchase/in_app_purchase.dart';

// import 'package:in_app_purchase_android/billing_client_wrappers.dart';
// import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/tools/cn_event_bus.dart';
import 'package:flutter_application_cyber/tools/cn_event_busUtils.dart';

class CnSCIAPManager {
  // 工厂方法构造函数,通过SingletonManager()获取对象
  factory CnSCIAPManager() => _getInstance();

  // instance的getter方法 - 通过SingletonManager.instance获取对象
  static CnSCIAPManager get instance => _getInstance();

  // 静态变量_instance，存储唯一对象
  static CnSCIAPManager? _instance;

  static get string => null;

  // 获取唯一对象
  static CnSCIAPManager _getInstance() {
    _instance ??= CnSCIAPManager._internal();
    return _instance!;
  }

//变量
  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  List<String> _kProductIds = <String>[];
  List<ProductDetails> _products = <ProductDetails>[];
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  String orderNo = '';

  //初始化
  CnSCIAPManager._internal() {
    //初始化其他操作...
    init();
  }

  init() {
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription =
        purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (Object error) {
      // handle error here.
    });
  }
  //方法

  /// 苹果内购 (购买)
  Future<void> applePay(Map dataMap) async {
    EasyLoading.show(status: 'loading...');
    orderNo = dataMap['orderNo'];

    /// _inAppPurchase是否有效
    final bool isAvailable = await _inAppPurchase.isAvailable();
    if (!isAvailable) {
      return;
    }

    /// 如果是iOS设备进行设置代理，接口苹果服务器的回调。
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());
    }

    /// 获取后台返回的产品id
    if (dataMap['goodsCode'] == null) {
      EasyLoading.dismiss();
      EasyLoading.showError('No product');
      return;
    }
    _kProductIds.add(dataMap['goodsCode']);

    /// 查询后台返回的ProductId是否在苹果服务器上注册了
    final ProductDetailsResponse productDetailResponse =
        await _inAppPurchase.queryProductDetails(_kProductIds.toSet());

    /// 查询不到说明没注册
    if (productDetailResponse.error != null) {
      EasyLoading.dismiss();
      EasyLoading.showError('Failed to obtain product information');
      return;
    }

    /// 查询不到商品详情说明没注册
    if (productDetailResponse.productDetails.isEmpty) {
      EasyLoading.dismiss();
      EasyLoading.showError('No product');
      return;
    }
    _products = productDetailResponse.productDetails;

    /// 查询成功
    ProductDetails productDetails = _products[0];
    late PurchaseParam purchaseParam;
    purchaseParam = PurchaseParam(
        productDetails: productDetails, applicationUserName: orderNo);

    /// 向苹果服务器发起支付请求
    _inAppPurchase.buyConsumable(purchaseParam: purchaseParam);
  }

//监听支付回调
  Future<void> _listenToPurchaseUpdated(
      List<PurchaseDetails> purchaseDetailsList) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        /// 等待购买中
      } else if (purchaseDetails.status == PurchaseStatus.canceled) {
        /// 取消订单
        _inAppPurchase.completePurchase(purchaseDetails);
        EasyLoading.dismiss();
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          /// 购买出错
          EasyLoading.dismiss();
          EasyLoading.showError('pay error');
          _inAppPurchase.completePurchase(purchaseDetails);
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          //调用苹果支付完成方法
          _inAppPurchase.completePurchase(purchaseDetails);
          /// 调用后台接口,发放商品
          deliverProduct(purchaseDetails);
        } else {
          _inAppPurchase.completePurchase(purchaseDetails);
        }
      }
    }
  }

  deliverProduct(PurchaseDetails purchaseDetails) async {
    // IMPORTANT!! Always verify purchase details before delivering the product.

    //判断是否有补单
    if (orderNo == '') {
      return;
    }

    var param = {
      'orderNo': orderNo, //支付订单号 ,创建订单返回的订单号
      "transactionId": purchaseDetails.purchaseID, //内购交易号 苹果返回的交易流水号
      "payload": purchaseDetails
          .verificationData.serverVerificationData, //支付有效载荷 ,苹果返回的购买凭证
      "type": "1"
    };
    // print("orderNo:${param}");

    CnNetHelper.paymentIpaData(param,
        (HDHResponseData resp, bool result, String msg) {
      EasyLoading.dismiss();
      if (result) {
        if (resp.code == 0 && resp.data) {
          EasyLoading.showSuccess('Pay Success！');
          EventBusUtils.getInstance()?.fire(EventKeys.applePaySuccess);
        } else {
          EasyLoading.showError('${resp.msg}');
        }
      } else {
        EasyLoading.showError('${resp.msg}');
      }
    });
  }
}

//代理方法
class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(
      SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) {
    return true;
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}
